package com.nineclock.auth.processor;

import cn.hutool.core.util.StrUtil;
import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
public class SMSAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    SysUserFeign userFeign;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        //用户名 == 手机号   密码： 验证码
        String mobile = entity.getAuthParameter("mobile");

        if(StrUtil.isEmpty(mobile)){
            throw new NcException(ResponseEnum.INVALID_PHONE_NUMBER);
        }
        //目前从数据库中查询到的是真正的 密码， 前端参数是 验证码（后期调整为动态生成， 目前先写死 1234）
        SysUserDTO userDto = userFeign.queryUser(mobile).getData();

        //设置固定的验证码
//        if(userDto != null){
//            //对固定验证码 加密
//            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//            userDto.setPassword(passwordEncoder.encode("1234"));
//        }
        //从redis 读取验证码
        if(userDto != null){
            //从redis 获取code
            String code = (String) redisTemplate.boundValueOps(SMSConstant.SMS_TYPE_LOGIN + mobile).get();

            //对固定验证码 加密
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            userDto.setPassword(passwordEncoder.encode(code));
        }
        return userDto;
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if(entity != null){
            if(entity.getAuthType() != null && "sms".equalsIgnoreCase(entity.getAuthType())){
                return true;
            }
        }
        return false;
    }
}
